﻿using System.Data;
using System.IO;

namespace RemoteTestRunner.DataAccess
{
    public class DataAccess
    {
        #region Private Attributes

        private RemoteTestRunner.DataAccess.RTRDataSet _dataSet;
        private string _dataPath;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="DataAccess"/> class.
        /// </summary>
        /// <param name="path">The path of the configuration to load.</param>
        public DataAccess(string path)
        {
            _dataPath = path;

            this.Load();
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Loads the saved configuration data from the specified path.
        /// </summary>
        public void Load()
        {
            _dataSet = new RTRDataSet();

            if (File.Exists(_dataPath))
            {
                _dataSet.ReadXml(_dataPath, XmlReadMode.ReadSchema);
                VerifyTestRecordStructure(_dataSet.Test);
            }
            else
            {
                // Initialize an empty DataSet
                _dataSet = new RTRDataSet();

                // Create the initial data file
                this.Save();
            }
        }

        /// <summary>
        /// Saves the current configuration to the data file.
        /// </summary>
        public void Save()
        {
            _dataSet.AcceptChanges();
            _dataSet.WriteXml(_dataPath, XmlWriteMode.WriteSchema);
        }

        /// <summary>
        /// Gets a list of configured projects.
        /// </summary>
        /// <returns>A <see cref="DataTable"/> containing a list of configured projects.</returns>
        public DataTable GetProjects()
        {
            return (DataTable)_dataSet.Project;
        }

        /// <summary>
        /// Gets a list of configured tests.
        /// </summary>
        /// <returns>A <see cref="DataTable"/> containing a list of configured tests.</returns>
        public DataTable GetTests()
        {
            VerifyTestRecordStructure(_dataSet.Test);
            return _dataSet.Test;
        }

        /// <summary>
        /// Gets a <see cref="DataRow"/> containing information for the specified test ID.
        /// </summary>
        /// <param name="testId">The test ID to retrieve information for.</param>
        /// <returns>A <see cref="DataRow"/> containing information for the specified test.</returns>
        public DataRow GetTestRow(int testId)
        {
            DataRow[] rows = _dataSet.Test.Select("ID = " + testId.ToString());

            if (rows.Length == 0)
            {
                return null;
            }
            else
            {
                VerifyTestRecordStructure(rows[0].Table);
                return rows[0];
            }
        }

        private void VerifyTestRecordStructure(DataTable table)
        {
            if (!table.Columns.Contains("RunConfigPath"))
            {
                table.Columns.Add(new DataColumn("RunConfigPath", typeof(string)));
            }
        }


        /// <summary>
        /// Deletes the specified test.
        /// </summary>
        /// <param name="testId">The ID of the test to be deleted.</param>
        public void DeleteTest(int testId)
        {
            DataRow[] rows = _dataSet.Test.Select("ID = " + testId.ToString());

            if (rows.Length > 0)
            {
                _dataSet.Test.RemoveTestRow((RemoteTestRunner.DataAccess.RTRDataSet.TestRow)rows[0]);
            }
        }

        /// <summary>
        /// Returns all configured test data (i.e. projects and tests).
        /// </summary>
        /// <returns>A <see cref="DataSet"/> containing a Project table and a Test table.</returns>
        public DataSet GetTestData()
        {
            DataSet dataSet = new RTRDataSet();

            if (File.Exists(_dataPath))
            {
                dataSet.ReadXml(_dataPath, XmlReadMode.ReadSchema);
                VerifyTestRecordStructure(dataSet.Tables["Test"]);
            }
            else
            {
                // Initialize an empty DataSet
                dataSet = new RTRDataSet();

                // Create the initial data file
                this.Save();
            }

            dataSet.Namespace = string.Empty;

            DataSet ds = new DataSet();

            foreach (DataTable table in dataSet.Tables)
            {
                ds.Tables.Add(table.Copy());
            }

            if (ds.Relations.Count == 0)
            {
                ds.Relations.Add("ProjectTest", ds.Tables["Project"].Columns["ID"], ds.Tables["Test"].Columns["ProjectID"]);
            }

            return ds;
        }

        /// <summary>
        /// Saves the test <see cref="DataSet"/> passed in.
        /// </summary>
        /// <param name="dataSet">The <see cref="DataSet"/> to be saved.</param>
        public void SaveTestData(DataSet dataSet)
        {
            dataSet.AcceptChanges();
            dataSet.WriteXml(_dataPath, XmlWriteMode.WriteSchema);
            Load();
        }

        /// <summary>
        /// Gets the project.
        /// </summary>
        /// <param name="projectId">The project id.</param>
        /// <returns></returns>
        public DataRow GetProject(int projectId)
        {
            DataRow[] matchingProjects = _dataSet.Tables["Project"].Select("ID = " + projectId);

            if (matchingProjects.Length != 1)
            {
                throw new System.ArgumentOutOfRangeException("projectId", "The specified Project ID was not found.");
            }

            return matchingProjects[0];
        }

        #endregion
    }
}
